package com.teamin.config;

import com.aliyun.oss.OSSClient;
import com.teamin.web.commandlinerun.InitCommandLine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.URL;
import java.util.Date;

/**
 * Created by e on 2017/11/21
 *
 * @author <a href="http://eregg.com">eregg</a>
 */
@Component
public class OSSUtil {



    // endpoint以杭州为例，其它region请按实际情况填写
    @Value("${oss.endpoint}")
    String endpoint;
    // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建
    @Value("${oss.appid}")
    String accessKeyId = "<yourAccessKeyId>";
    @Value("${oss.secret}")
    String accessKeySecret = "<yourAccessKeySecret>";
    @Value("${oss.buckname}")
    String bucketName = "<yourBucketName>";

    /**
     * 根据key获取url地址
     * @param key
     * @return
     * @throws Exception
     */
    public String getUrlByKey(String key) throws Exception{
        String urlStr = null;
        // 创建OSSClient实例
        Long expir = System.currentTimeMillis()+3600*1000;
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        URL url = ossClient.generatePresignedUrl(bucketName, key, new Date(expir));
        urlStr = url.toString();
        // 关闭client
        ossClient.shutdown();
        return urlStr;
    }

}
